package com.wangxq.loginmodule.yd_login.login.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.delegate.sys.SysInfo;
import com.jess.arms.database.MMkvHelper;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.utils.ArmsUtils;

import com.wangxq.loginmodule.R;
import com.wangxq.loginmodule.yd_login.login.di.component.DaggerSettingComponent;
import com.wangxq.loginmodule.yd_login.login.di.module.SettingModule;
import com.wangxq.loginmodule.yd_login.login.mvp.contract.SettingContract;
import com.wangxq.loginmodule.yd_login.login.mvp.presenter.SettingPresenter;
import com.wangxq.mylibrary.dialog.DialogTools;

import javax.inject.Inject;

import butterknife.BindView;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class SettingActivity extends BaseActivity<SettingPresenter> implements SettingContract.View {
    Toolbar menuTp;
    EditText etServerAddress;
    EditText etWebSocketAddress;
    CardView cvChangeWebSocket;
//    @Inject
//    Retrofit retrofit;
    @Inject
    OkHttpClient okHttpClient;
    @Inject
    HttpUrl apiUrl;
    @Inject
    IRepositoryManager repositoryManager;
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSettingComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .settingModule(new SettingModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_setting; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initViews();
        setTranslucentStatus();
        setSupportActionBar(menuTp);
        menuTp.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        String url = MMkvHelper.getInstance().getBaseUrl();
        String webSocketUrl = MMkvHelper.getInstance().getWebsocketUrl();
        if (!StringUtils.isTrimEmpty(url)) {
            etServerAddress.setText(url);
        } else {
            etServerAddress.setText("http://192.168.0.1:8080/");
        }
        if (!StringUtils.isTrimEmpty(webSocketUrl)) {
            etWebSocketAddress.setText(webSocketUrl);
        } else {
            etWebSocketAddress.setText("http://192.168.0.1:8080/");
        }
        if (!MMkvHelper.getInstance().getWebSocketVisible()){
            cvChangeWebSocket.setVisibility(View.GONE);
        } else {
            cvChangeWebSocket.setVisibility(View.VISIBLE);
        }

    }

    private void initViews() {
        menuTp=findViewById(R.id.menu_tp);
        etServerAddress=findViewById(R.id.etServerAddress);
        etWebSocketAddress=findViewById(R.id.etWebSocketAddress);
        cvChangeWebSocket=findViewById(R.id.cvChangeWebSocket);

    }

    @Override
    public void showLoading() {
        DialogTools.INSTANCE.showLoading(getSupportFragmentManager());
    }

    @Override
    public void hideLoading() {
        DialogTools.INSTANCE.dismissLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.change_server_bar_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.iv_right) {
            if (etServerAddress.getText() == null || etServerAddress.getText().toString().equals("")) {
                ToastUtils.showShort("还未输入地址");
                return false;
            }
            String url = etServerAddress.getText().toString();
            String webSocketUrl = etWebSocketAddress.getText().toString();
            if (url.toLowerCase().startsWith("http://")||url.toLowerCase().startsWith("https://")) {
//                showMessage("请输入服务器地址(IP、端口号)");
//                return true;
            }else {
                showMessage("请输入服务器地址(IP、端口号)");
                return false;
            }
//            修改服务器地址后删除上个服务器数据
            //消息服务器地址
            String busServerUrl = url;
            MMkvHelper.getInstance().removeBaseUrl();
            MMkvHelper.getInstance().saveWebsocketUrl(webSocketUrl);
            MMkvHelper.getInstance().saveBaseUrl(busServerUrl);
            MMkvHelper.getInstance().saveLoginUrl(SysInfo.loginURL);
            Log.e("保存",busServerUrl+"/"+ SysInfo.loginURL);
            apiUrl = HttpUrl.parse(busServerUrl);
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                    .serializeNulls()
                    .create();
            repositoryManager.setRetrofit(new Retrofit.Builder().baseUrl(apiUrl).client(okHttpClient)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson)).build());
            ToastUtils.showShort("修改成功");
            finish();
        }

        return super.onOptionsItemSelected(item);
    }

}
